<template>
  <div ref="multi_line_chart" />
</template>

<script>
import * as echarts from 'echarts'
import resize from '@/components/Mixins/resize'

export default {
  name: 'MultiLineChart',
  mixins: [resize],
  props: {
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.multi_line_chart)
      this.setOptions(this.chartData)
    },
    setOptions({ dataList, dateList, title } = {}) {
      const legendData = []
      const seriesData = []
      for (let i = 0; i < dataList.length; i++) {
        let name
        if (dataList[i]['unit']) {
          name = dataList[i]['name'] + '(' + dataList[i]['unit'] + ')'
        } else {
          name = dataList[i]['name']
        }
        legendData.push(name)
        seriesData.push({
          name: name,
          smooth: true,
          type: 'line',
          data: dataList[i]['dataList'],
          animationDuration: 2000,
          animationEasing: 'cubicInOut'
        })
      }
      const option = {
        xAxis: {
          type: 'category',
          data: dateList
          // axisPointer: {
          //   value: 1,
          //   snap: true,
          //   lineStyle: {
          //     color: '#004E52',
          //     opacity: 0.5,
          //     width: 2
          //   },
          //   label: {
          //     show: true,
          //     backgroundColor: '#004E52'
          //   },
          //   handle: {
          //     show: true,
          //     color: '#004E52'
          //   }
          // },
          // splitLine: {
          //   show: false
          // },
          // axisLine: {
          //   lineStyle: {
          //     color: '#909399'
          //   }
          // }
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 20
          // top: 5
          // containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#FFF',
          axisPointer: {
            type: 'cross'
          }
          // padding: [5, 10]
        },
        yAxis: {
          show: false
        },
        legend: {
          data: legendData
        },
        series: seriesData
      }
      if (title != null) {
        option.title = {
          text: title
        }
      }
      this.chart.setOption(option)
    }
  }
}
</script>
